<template>
  <div class="switch" @click="toggle">
    <div class="switch-slider" :class="{ 'on': modelValue }"></div>
  </div>
</template>

<script>
import { defineComponent, watch } from 'vue';

export default defineComponent({
  name: 'Switch',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    // 监听 modelValue 的变化并同步更新
    watch(
      () => props.modelValue,
      (val) => {
        emit('update:modelValue', val);
      }
    );
    // toggle 方法用于切换开关状态
    const toggle = () => {
      emit('update:modelValue', !props.modelValue);
    };
    return {
      toggle
    };
  }
});
</script>

<style>
.switch {
  display: inline-block;
  position: relative;
  width: 50px;
  height: 25px;
  border-radius: 15px;
  background-color: #5a5a5a;
  cursor: pointer;
  margin-top: 10px;
}

.switch-slider {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 21px;
  height: 21px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.4);
  transition: all 0.2s ease-in-out;
}

.switch-slider.on {
  left: 27px;
}
</style>